package com.zx.converter.reference;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.zx.converter.Converter;
import com.zx.exception.DataParseException;

/**
 * @Project: dataParse-core
 * @Title: IntegerConverter
 * @Description: 引用类型转换器--String
 * @author: zhangxue
 * @date: 2019年1月12日下午10:24:34
 * @company: 未知之地
 * @Copyright: Copyright (c) 2019
 * @version v1.0
 */
public class DateConverter implements Converter<Date> {
	
	/**
	 *  SimpleDateFormat 是数据不安全的
	 */
	private static final ThreadLocal<SimpleDateFormat> LOCAL_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>();
	
	private String datePattern;
	
	public DateConverter(String datePattern) {
		this.datePattern = datePattern;
	}

	@Override
	public Date convertValue(Object obj) throws DataParseException {
		if(obj == null) {
			throw new NullPointerException();
		}
		
		// 当前线程没有初始化格式转化器
		SimpleDateFormat dateFormat = LOCAL_DATE_FORMAT.get();
		if(dateFormat == null) {
			dateFormat = new SimpleDateFormat(this.datePattern);
			LOCAL_DATE_FORMAT.set(dateFormat);
		}
		
		Date result = null;
		try {
			result = dateFormat.parse(obj.toString());
		} catch (Exception e) {
			throw new DataParseException(e, "类型转换异常: " + obj.toString());
		}
		
		return result;
	}

	@Override
	public Class<Date> getTargetType() {
		return Date.class;
	}
	
}
